using System.Linq.Expressions;
using Microsoft.SharePoint;

namespace Sapphire.Linq.Framework
{
    public class ExpressionHelper
    {
        public static IListQuery GetListQuery(Expression expression)
        {
            return GetListQuery(expression as MethodCallExpression);
        }

        private static IListQuery GetListQuery(MethodCallExpression methodCallExpression)
        {
            var constantExpression = methodCallExpression.Arguments[0] as ConstantExpression;

            if (constantExpression != null)
            {
                return GetListQuery(constantExpression);
            }

            return GetListQuery(methodCallExpression.Arguments[0] as MethodCallExpression);
        }

        private static IListQuery GetListQuery(ConstantExpression constantExpression)
        {
            return constantExpression.Value as IListQuery;
        }

        public static SPList GetList(Expression expression)
        {
            return GetListQuery(expression).List;
        }
    }
}